package crawler.extension.ocr.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import crawler.extension.ocr.configure.LocalConfigure;
import crawler.extension.ocr.service.FileService;
import crawler.extension.ocr.service.OCRService;

@RestController
@RequestMapping("/crawler/extension/ocr")
public class OCRController {
	
	@Autowired
	private OCRService ocrService;
	@Autowired
	private FileService fileService;
	
	@GetMapping(value = "/url")
    public String urlText(HttpServletRequest request, HttpServletResponse response,
    		@RequestParam(value = "url", required = true) String url,
    		@RequestParam(value = "website", required = false) String website,
    		@RequestParam(value = "contrast", required = false) String contrast) {
		
		String fileName = ocrService.fetchPic(url, website);
		String ocrResult = ocrService.getOCR(fileName, website, contrast);

		return ocrResult;
    } 
	
   
    @PostMapping(value = "/upload")
    public String photoUpload(HttpServletRequest request, HttpServletResponse response,
    		@RequestParam(value = "file", required = true) MultipartFile file,
    		@RequestParam(value = "website", required = false) String website,
    		@RequestParam(value = "contrast", required = false) String contrast) {
       
    	Map<String, String> resultMap = fileService.save(file, website);
    	String result = resultMap.get("result");
    	String ocrResult = "";
    	if ("success".equals(result)) {
    		String fileName = resultMap.get("fileName");
    		ocrResult = ocrService.getOCR(fileName, website, contrast);
		}
    	
		return ocrResult;
    }
}
